/**
 * Author:yuiop
 * Date:2022/8/26 09:50
 */
package com.devops.admin.collector;

import com.devops.admin.service.DOSLogRecordService;
import com.devops.admin.service.DOSMetricsService;
import com.devops.admin.service.DOSReleaseService;
import io.prometheus.client.Collector;
import io.prometheus.client.CounterMetricFamily;
import io.prometheus.client.GaugeMetricFamily;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;

public class DevopsCollector extends Collector {

    @Autowired
    DOSLogRecordService dosLogRecordService;
    @Autowired
    DOSReleaseService dosReleaseService;
    @Autowired
    DOSMetricsService dosMetricsService;
    @Override
    public List<MetricFamilySamples> collect() {
        List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
        // With no labels.
        if (dosLogRecordService != null) {
            mfs.add(new CounterMetricFamily("devops_request", "devops request total", dosLogRecordService.count()));
        }

        // With labels
        if (dosReleaseService != null) {
            mfs.add(new GaugeMetricFamily("devops_release_count", "devops release count", dosReleaseService.count()));
            List<String> labelList = Arrays.asList("groupname","projectname");
            List<HashMap<String,Object>> groupReleases = dosReleaseService.getGroupRelease();
            GaugeMetricFamily labeledGauge = new GaugeMetricFamily("devops_project_release", "devops project release",labelList);
            groupReleases.forEach(map -> {
                ArrayList<String> valueList = new ArrayList<>();
                labelList.forEach(label -> {
                    valueList.add(map.get(label).toString());
                });
                labeledGauge.addMetric(valueList,Integer.parseInt(map.get("releasecount").toString()));
            });
            mfs.add(labeledGauge);
        }

        return mfs;
    }


}
